package com.chenggong.window.activity.module

import android.content.Context
import android.os.Bundle
import android.text.ClipboardManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import androidx.core.view.isVisible
import com.chenggong.log.LogDebugUtil
import com.chenggong.retrofit.bean.GithubBean
import com.chenggong.retrofit.retrofit.ApiService
import com.chenggong.retrofit.retrofit.ApiServiceManager
import com.chenggong.retrofit.rxjava.ApiRxjavaService
import com.chenggong.retrofit.rxjava.ApiRxjavaServiceManager
import com.chenggong.window.R
import com.chenggong.window.base.BaseActivity
import com.chenggong.window.databinding.ActivityModuleRetrofitBinding
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ModuleRetrofitActivity: BaseActivity<ActivityModuleRetrofitBinding>() {

    private lateinit var adapter: ArrayAdapter<String>
    override val layoutId: Int
        get() = R.layout.activity_module_retrofit

    override fun initView(savedInstanceState: Bundle?) {

        val data = arrayOf(
            getString(R.string.text_retrofit),
            getString(R.string.text_rxjava),
            getString(R.string.text_retrofit_rxjava),
        )
        adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, data)
        val listView = findViewById<ListView>(R.id.list)
        listView.adapter = adapter
        listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            onItemClick(position)
        }

        mDataBinding.ivClose.setOnClickListener {
            mDataBinding.llInstructions.isVisible = false
        }
        mDataBinding.ivCopy.setOnClickListener {
            copyString(mDataBinding.tvContent.text.toString())
        }
    }

    private fun onItemClick(position: Int) {
        mDataBinding.tvContent.text = ""
        val value = adapter.getItem(position)
        when(value){
            getString(R.string.text_retrofit) -> {

                //发送异步请求
                //创建网络请求接口的实例
                val apiService = ApiServiceManager.get().create(ApiService::class.java)
                //对发送请求进行封装
                val call: Call<GithubBean> = apiService.getGithubData("hongyangAndroid")
                call.enqueue(object : Callback<GithubBean?> {

                    override fun onResponse(
                        call: Call<GithubBean?>,
                        response: Response<GithubBean?>,
                    ) {
                        //网络请求成功
                        response.body()?.let {
                            mDataBinding.llInstructions.isVisible = true
                            mDataBinding.tvContent.text = "网络请求成功：\n${it.toString()}\n\n" +
                                    "https://gitee.com/liaoyucheng/chenggong/tree/master/retrofitTool"
                        }
                    }

                    override fun onFailure(call: Call<GithubBean?>, t: Throwable) {
                        //网络请求失败
                        mDataBinding.llInstructions.isVisible = true
                        mDataBinding.tvContent.text = t.message
                    }

                })

            }

            getString(R.string.text_rxjava) -> {
                Observable.create(ObservableOnSubscribe<Int> { e ->
                    val result = 5
                    mDataBinding.llInstructions.isVisible = true
                    mDataBinding.tvContent.append("result = 5\n")
                    e.onNext(result)
                    e.onComplete()
                }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(object : Observer<Int> {
                        override fun onSubscribe(d: Disposable?) {
                            //首先执行这里,做一些逻辑判断，可以取消订阅
                            //d?.dispose()//取消订阅,不会执行onNext
                            mDataBinding.llInstructions.isVisible = true
                            mDataBinding.tvContent.append("onSubscribe\n")
                        }
                        override fun onNext(value: Int) {
                            mDataBinding.llInstructions.isVisible = true
                            mDataBinding.tvContent.append("onNext($value)\n")
                        }
                        override fun onError(e: Throwable?) {}
                        override fun onComplete() {
                            mDataBinding.llInstructions.isVisible = true
                            mDataBinding.tvContent.append("onComplete()\n\n")
                            mDataBinding.tvContent.append("https://gitee.com/liaoyucheng/chenggong/tree/master/retrofitTool")
                        }
                    })
            }

            getString(R.string.text_retrofit_rxjava) -> {

                //发送异步请求
                //创建网络请求接口的实例
                val apiService = ApiRxjavaServiceManager.get().create(ApiRxjavaService::class.java)
                //retrofit2+rxjava2
                apiService.getGithubData("hongyangAndroid")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<GithubBean?> {
                        override fun onSubscribe(d: Disposable?) {
                        }

                        override fun onNext(response: GithubBean?) {
                            //网络请求成功
                            response?.let {
                                mDataBinding.llInstructions.isVisible = true
                                mDataBinding.tvContent.text = "网络请求成功：\n${it.toString()}\n\n" +
                                        "https://gitee.com/liaoyucheng/chenggong/tree/master/retrofitTool"
                            }
                        }

                        override fun onError(e: Throwable?) {
                            //网络请求失败
                            mDataBinding.llInstructions.isVisible = true
                            mDataBinding.tvContent.text = e?.message
                        }

                        override fun onComplete() {
                        }
                    })

            }
        }
        LogDebugUtil.d(value)
    }

    override fun onBackPressed() {
        if(mDataBinding.llInstructions.isVisible){
            mDataBinding.llInstructions.isVisible = false
            return
        }
        super.onBackPressed()
    }

    private fun copyString(content: String) {
        val cm = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        cm.text = content
        Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show()
    }
}